package com.base.monitor.module.biz.handler;

import com.base.monitor.framework.result.Result;
import com.base.monitor.module.biz.context.CfgContext;
import com.base.monitor.module.biz.properties.ParamProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 这个handler是用来推送网关在线时间的
 */
@Component
@Slf4j
@EnableConfigurationProperties(ParamProperties.class)
public class UpdateOnlineTimeHandler implements InitializingBean {

    @Autowired
    private ParamProperties paramProperties;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public void afterPropertiesSet() throws Exception {
        ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(2);
        scheduledExecutorService.scheduleWithFixedDelay(new UpdateOnlineTimeTask(), 30, 30, TimeUnit.SECONDS);
    }

    private class UpdateOnlineTimeTask implements Runnable {
        @Override
        public void run() {
            log.info("开始发送请求推送在线时间");
            Map<Long, Date> gatewayOnlineMap = CfgContext.getGatewayOnlineMap();
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Map<Long, Date>> requestEntity = new HttpEntity<>(gatewayOnlineMap, requestHeaders);
            try {
                restTemplate.postForEntity(paramProperties.getUploadOnlineTimeUrl(), requestEntity, Result.class);
                log.info("推送在线时间的请求发送成功");
            } catch (Exception e) {
                log.error("推送在线时间的请求发送失败，原因是：{}", e.getMessage());
            }
        }

    }
}
